// pages/coupon/detail/detail.js
var app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    id: '',
    detail: {}
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      id: options.id
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.getAllCoupon()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    let that = this
    return {
      title: that.data.detail.product_name + '满' + that.data.detail.use_price + '元使用',
    }
  },

  getAllCoupon: function() {
    let that = this

    wx.showLoading({
      mask: true,
      title: app.globalData.loadText,
    })

    app.getAccessToken(app.getPageUrl(getCurrentPages())).then(function (accessToken) {
      wx.request({
        url: app.globalData.hostAPI + '/v1/coupon/get-by-id?access_token=' + accessToken,
        data: {
          coupon_id: that.data.id
        },
        success: res => {
          if (res.data.status === 1) {
            that.setData({
              detail: res.data.data
            },() => {
              wx.hideLoading()
            })
          }
        }
      })
    })
  },

  exchagePoint: function() {
    let that = this
    wx.showLoading({
      mask: true,
      title: app.globalData.loadText,
    })
    app.getAccessToken(app.getPageUrl(getCurrentPages())).then(function (accessToken) {
      wx.request({
        url: app.globalData.hostAPI + '/v1/customer/receive-give-coupon?access_token=' + accessToken,
        data: {
          coupon_id: that.data.id,
        },
        success: res => {
          if (res.data.status === 1) {
            wx.hideLoading()
            wx.showModal({
              title: '提示',
              content: '领取成功',
              success: res => {
                wx.redirectTo({
                  url: '/pages/coupon/coupon',
                })
              }
            })
          } else {
            wx.hideLoading()
            wx.showToast({
              title: res.data.msg,
            })
          }
        }
      })
    })
  }
})